//
//  NetworkManager.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/23.
//

import Foundation
import Moya

class TencentNetManager {
    static let shared = TencentNetManager()
    
    private let provider: MoyaProvider<TencentNetApi>
    
    private init() {
        provider = MoyaProvider<TencentNetApi>()
    }
    //统一请求处理
    private func request<M: Codable>(_ target: TencentNetApi, modeType: M.Type) async throws-> M {
        try await withCheckedThrowingContinuation({ continuation in
            provider.request(target) { result in
                //调用统一接口处理
                dealNetResult(result: result, modeType: modeType) {
                    continuation.resume(returning: $0)
                } fail: {
                    continuation.resume(throwing: $0)
                }
            }
        })
    }
}

//接口请求
extension TencentNetManager {
    
    /**
     *  获取微信token
     */
    func getWxToken<M: Codable>(appid: String, secret: String, code: String, grant_type: String, modeType: M.Type) async throws-> M {
        let api : TencentNetApi = .wxToken(appid: appid, secret: secret, code: code, grant_type: grant_type)
        return try await request(api, modeType: modeType)
    }
    
    /**
     *  获取微信用户信息
     */
    func getWxInfo<M: Codable>(access_token: String, openid: String, modeType: M.Type) async throws-> M {
        let api : TencentNetApi = .wxInfo(access_token: access_token, openid: openid)
        return try await request(api, modeType: modeType)
    }
    
    /**
     *  获取QQ用户信息
     */
    func getQQInfo<M: Codable>(access_token: String, openid: String, appId:String, modeType: M.Type) async throws-> M {
        let api : TencentNetApi = .qqInfo(access_token: access_token, openid: openid, appId: appId)
        return try await request(api, modeType: modeType)
    }
   
}
